package org.test.ping.service.impl;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.test.ping.Utils.RateLimiterUtil;
import org.test.ping.service.PingService;

import javax.annotation.Resource;

/**
 * @ClassName PingServiceImpl
 * @Description TODO
 * @Author JiaLin
 * @Date 2024/11/21 1:28
 */
@Slf4j
@Service
public class PingServiceImpl implements PingService {

    @Resource
    private WebClient webClient;

    private final String DEPARTMENT_SERVICE = "http://localhost:8083";
    RateLimiter limiter = RateLimiter.create(2); // 限速器,每秒2个令牌
    @Override
    public String sayHello(){
        String result = "";
        log.info("********************");
        //并发
        if (RateLimiterUtil.tryLock("lock.txt", 1L))
        {
            if (limiter.tryAcquire()){
                log.info("Ping Request Hello");
                try {
                    result = webClient.get()
                            .uri(DEPARTMENT_SERVICE+"/pong")
                            .retrieve()
                            .bodyToMono(String.class)
                            .block();
                }catch (Exception e) {
                    log.info("Pong service unavailable...");
                    result = "430 Rate limited, Pong throttled it";
                }
                log.info(result);
            }else{
                log.warn("Ping Request Sent, Rate limited.");
            }
        }else{
            log.warn("429 Too Many Requests");
            log.warn("430 Rate limited, Pong throttled it");
        }
        log.info("********************");
        return result;
    }

}
